#!/usr/bin/env python3
"""
调试应用启动脚本
"""
import os
import sys

def debug_app():
    """调试应用启动"""
    print("🔍 开始调试Flask应用...")
    
    # 检查当前目录
    print(f"📂 当前工作目录: {os.getcwd()}")
    
    # 检查Python路径
    print(f"🐍 Python路径: {sys.executable}")
    
    # 检查环境变量
    print("\n🔧 环境变量检查:")
    env_vars = ['MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DB', 'JWT_SECRET_KEY']
    for var in env_vars:
        value = os.getenv(var, '未设置')
        if var == 'MYSQL_PASSWORD':
            value = '***' if value != '未设置' else '未设置'
        print(f"   {var}: {value}")
    
    # 尝试导入模块
    print("\n📦 模块导入检查:")
    try:
        from app import create_app
        print("   ✅ app 模块导入成功")
    except Exception as e:
        print(f"   ❌ app 模块导入失败: {e}")
        return
    
    try:
        from models import db, User
        print("   ✅ models 模块导入成功")
    except Exception as e:
        print(f"   ❌ models 模块导入失败: {e}")
        return
    
    try:
        from router.auth import auth_bp
        print("   ✅ auth 路由导入成功")
    except Exception as e:
        print(f"   ❌ auth 路由导入失败: {e}")
        return
    
    # 创建应用
    print("\n🚀 创建Flask应用:")
    try:
        app = create_app('development')
        print("   ✅ Flask应用创建成功")
        
        # 检查路由
        print("\n🛣️  路由检查:")
        with app.app_context():
            for rule in app.url_map.iter_rules():
                if 'auth' in rule.rule:
                    methods = ', '.join(sorted(rule.methods - {'HEAD', 'OPTIONS'}))
                    print(f"   {rule.rule:<30} -> {methods}")
        
        # 测试数据库连接
        print("\n🗄️  数据库连接测试:")
        try:
            with app.app_context():
                # 尝试查询用户表
                user_count = User.query.count()
                print(f"   ✅ 数据库连接成功，用户数量: {user_count}")
        except Exception as e:
            print(f"   ❌ 数据库连接失败: {e}")
            print("   💡 请检查MySQL服务是否运行，数据库是否存在")
        
        print("\n🎯 应用启动测试:")
        print("   如果上述检查都通过，可以尝试启动应用:")
        print("   python app.py")
        
    except Exception as e:
        print(f"   ❌ Flask应用创建失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    debug_app()
